/*
 * 显示用户名字
 * */
var loadBody = function () {
    var uid = sessionStorage.getItem("uid");
    if(uid == null){
        alert("请先登录系统");
        sessionStorage.clear();
        $.cookie("access_token", null, {path: "/"});
        location.href = "login.html";
    }
    document.getElementById("maternity_name").innerHTML = sessionStorage.getItem("maternity_name");
};

// /*
//  *获取焦点刷新页面
//  */
// window.onfocus = function(){
//     location.reload(true);
// }
/*
 * 登出
 * */
var logout = function () {
    sessionStorage.clear();
    $.cookie("access_token", null, {path: "/"});
    location.href = "login.html";
}

var detailPage;
var addMatronPage;

/*
 * 将加载数据封装为一个服务
 * */
var app = angular.module('myApp', []);
app.factory('loadDataService', function ($http, $q) {

    var service = {};

    //获取uid以及access_token
    var access_token = $.cookie("access_token");
    var uid = sessionStorage.getItem("uid");

    //获取并返回数据
    service.loadData = function (param) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        //返回的数据对象
        var information = new Object();

        $http({
            method: "post",
            url: ip + "yuesao/list",
            data: {
                uid: uid,
                access_token: access_token,
                page: param.cur_page,
                per_page: param.per_page,
                order_by: param.sort_by,
                is_ascend: param.is_ascend,
                filter: param.filter
            }
        }).success(function (data, status, headers, config) {
            if (data.success) {
                //将数据存储为一个对象返回
                information.matrons = data.data.records;
                information.total_count = data.data.total_count;
                deferred.resolve(information);
            }
            else {
                alert(data.msg);
                if (data.msg == "登录状态已失效,请重新登录") {
                    sessionStorage.clear();
                    $.cookie("access_token", null, {path: "/"});
                    location.href = "login.html";
                }
            }
        });
        return promise;
    };

    //搜索并返回数据
    service.searchData = function (name, param) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        //返回的数据对象
        var information = new Object();

        $http({
            method: "post",
            url: ip + "yuesao/" + name + "/list",
            data: {
                uid: uid,
                access_token: access_token,
                page: param.cur_page,
                per_page: param.per_page,
                order_by: param.sort_by,
                is_ascend: param.is_ascend,
                filter: param.filter
            }
        }).success(function (data, status, headers, config) {
            if (data.success) {
                //将数据存储为一个对象返回
                information.matrons = data.data.records;
                information.total_count = data.data.records_count;
                deferred.resolve(information);
            }
            else {
                alert(data.msg);
                if (data.msg == "登录状态已失效,请重新登录") {
                    sessionStorage.clear();
                    $.cookie("access_token", null, {path: "/"});
                    location.href = "login.html";
                }
            }
        });
        return promise;
    }

    return service;
});

app.controller('filterCtrl', function ($scope, $http, loadDataService) {
    // 加载省市数据
    $scope.provinces = cityList;
    $scope.changeProvince = function () {
        if ($scope.province!=null) {
            $scope.cities = $scope.province.c;
            $scope.useFilter = true;
        }
        else $scope.cities = null;
    };
    var numOfPages = 0;
    //列表模式与头像模式的切换
    var isHeadImgModel = false;
    var isAllSelected = false;
    $scope.setImgModel = function () {
        isHeadImgModel = true;
        document.getElementById("head_img_model").src = "img/head-img-model-select.png";
        document.getElementById("list_model").src = "img/list-model-unselect.png";
    }
    $scope.setListModel = function () {
        isHeadImgModel = false;
        document.getElementById("head_img_model").src = "img/head-img-model-unselect.png";
        document.getElementById("list_model").src = "img/list-model-select.png";
    }
    $scope.getModel = function () {
        return isHeadImgModel;
    }

    $scope.selectAll = function () {
        var checks = document.getElementsByName("mycheckbox");
        var content = document.getElementById("select_all");
        if (isAllSelected) {
            content.innerHTML = "全选";
            for (var i = 0; i < checks.length; i++) {
                checks[i].checked = false;
            }
            isAllSelected = false;
        }
        else {
            content.innerHTML = "取消";
            for (var i = 0; i < checks.length; i++) {
                checks[i].checked = true;
            }
            isAllSelected = true;
        }
    };
    $scope.onNameClick = function (mid) {
        window.open('../training/maintain_score.html#?mid=' + mid);
    };

    //存储过滤信息
    var param = {};
    param.cur_page = 1;
    param.per_page = 20;
    param.sort_by = "mid";
    param.is_ascend = true;
    param.filter = null;

    //用于记录升序还是降序排列
    var is_id_ascend = true;
    var is_name_ascend = true;
    var is_age_ascend = true;
    var is_province_ascend = true;
    var is_level_ascend = true;
    var is_experience_ascend = true;
    var is_star_ascend = true;
    var is_grade_count_ascend = true;

    /*
     * 搜索月嫂
     * */
    $scope.search = function () {
        var name = $scope.matron_name;
        //加载并显示数据
        $scope.matrons = loadDataService.searchData(name, param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });
    }

    /*
     * 控制全部删除的出现
     * */
    $scope.isMultiSel = function () {
        var checks = document.getElementsByName("mycheckbox");
        var n = 0;
        for (var i = 0; i < checks.length; i++) {
            if (checks[i].checked)
                n++;
        }
        if (n > 1) {
            return true;
        }
        else {
            return false;
        }
    }

    /*
     * 跳转到添加月嫂页面
     * */
    $scope.turn2Add = function () {
        // if (addMatronPage == null || addMatronPage.closed)
        addMatronPage = window.open("add_matron.html");
        // else {
        //     addMatronPage.location.reload();
        //     addMatronPage.focus();
        // }
    };

    /*
     * 跳转到月嫂信息页面
     * */
    $scope.turn2Info = function (id) {
        sessionStorage.setItem("matron_id", id);
        // if (detailPage == null || detailPage.closed)
        detailPage = window.open("matron_info.html");
        // else {
        //     detailPage.location.reload();
        //     detailPage.focus()
        // }
    };

    /*
     * 删除id对应月嫂
     * */
    $scope.delete = function (id) {
        //删除确认
        var msg = "确定删除该月嫂吗？";
        if (confirm(msg) == true) {
            //获取uid以及access_token
            var access_token = $.cookie("access_token");
            var uid = sessionStorage.getItem("uid");

            $http({
                method: "post",
                url: ip + "yuesao/delete",
                data: {
                    uid: uid,
                    access_token: access_token,
                    id: [
                        id
                    ]
                }
            }).success(function (data, status, headers, config) {
                if (data.success) {
                    //更新并显示数据
                    $scope.matrons = loadDataService.loadData(param).then(function (result) {
                        $scope.matrons = result.matrons;
                        var pageNum = Math.ceil(result.total_count / param.per_page);
                        numOfPages = pageNum;
                        var pageList = [];
                        for (var i = 0; i < pageNum; i++) {
                            pageList.push(i + 1);
                        }
                        $scope.pages = pageList;
                    });
                }
                else {
                    alert(data.msg);
                    if (data.msg == "登录状态已失效,请重新登录") {
                        sessionStorage.clear();
                        $.cookie("access_token", null, {path: "/"});
                        location.href = "login.html";
                    }
                }
            });
        }
    }

    /*
     * 批量删除月嫂
     * */
    $scope.deleteAll = function () {
        //删除确认
        var msg = "确定删除选中的所有月嫂吗？";
        if (confirm(msg) == true) {
            //获取uid以及access_token
            var access_token = $.cookie("access_token");
            var uid = sessionStorage.getItem("uid");

            //待删除id列表
            var id_delete = new Array();

            //获取月嫂id列表
            var checks = document.getElementsByName("mycheckbox");
            for (var i = 0; i < checks.length; i++) {
                if (checks[i].checked) {
                    id_delete.push(checks[i].parentNode.nextSibling.nextSibling.innerText);
                }
            }

            $http({
                method: "post",
                url: ip + "yuesao/delete",
                data: {
                    uid: uid,
                    access_token: access_token,
                    id: id_delete
                }
            }).success(function (data, status, headers, config) {
                if (data.success) {
                    //更新并显示数据
                    $scope.matrons = loadDataService.loadData(param).then(function (result) {
                        $scope.matrons = result.matrons;
                        var pageNum = Math.ceil(result.total_count / param.per_page);
                        numOfPages = pageNum;
                        var pageList = [];
                        for (var i = 0; i < pageNum; i++) {
                            pageList.push(i + 1);
                        }
                        $scope.pages = pageList;
                    });

                }
                else {
                    alert(data.msg);
                    if (data.msg == "登录状态已失效,请重新登录") {
                        sessionStorage.clear();
                        $.cookie("access_token", null, {path: "/"});
                        location.href = "login.html";
                    }
                }
            });
        }
    }

    /*
     * 增加减少星级
     * */

    $scope.add_star = function () {
        var level = document.getElementById("level").innerHTML;
        if(level == "全部"){
            document.getElementById("level").innerHTML = 1;
        }
        else{
            level = parseInt(level);
            if (level <= 4) {
                level = level + 1;
                document.getElementById("level").innerHTML = level;
            }
            else{
                document.getElementById("level").innerHTML = "全部";
            }
        }
    };
    $scope.minus_star = function () {
        var level = document.getElementById("level").innerHTML;
        if(level == "全部"){
            document.getElementById("level").innerHTML = 5;
        }
        else{
            level = parseInt(level);
            if (level >= 2) {
                level -= 1;
                document.getElementById("level").innerHTML = level;
            }
            else {
                alert("最低可选星级为一星！");
            }
        }
    };

    $scope.show_filter = false;//默认不显示筛选栏

    //获取uid以及access_token
    var access_token = $.cookie("access_token");
    var uid = sessionStorage.getItem("uid");

    //加载并显示数据
    $scope.matrons = loadDataService.loadData(param).then(function (result) {
        $scope.matrons = result.matrons;
        var pageNum = Math.ceil(result.total_count / param.per_page);
        numOfPages = pageNum;
        var pageList = [];
        for (var i = 0; i < pageNum; i++) {
            pageList.push(i + 1);
        }
        $scope.pages = pageList;
    });

    //设置排序方式
    $scope.sort_by_id = function () {
        param.is_ascend = is_id_ascend;
        param.sort_by = "mid";

        //更新并显示数据
        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });
        is_id_ascend = !is_id_ascend;
    };
    $scope.sort_by_name = function () {
        param.is_ascend = is_name_ascend;
        param.sort_by = "name";

        //更新并显示数据
        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });

        is_name_ascend = !is_name_ascend;
    };
    $scope.sort_by_age = function () {
        param.is_ascend = is_age_ascend;
        param.sort_by = "age";

        //更新并显示数据
        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });

        is_age_ascend = !is_age_ascend;
    };
    $scope.sort_by_province = function () {
        param.is_ascend = is_province_ascend;
        param.sort_by = "native_place";

        //更新并显示数据
        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });

        is_province_ascend = !is_province_ascend;
    };
    $scope.sort_by_level = function () {
        param.is_ascend = is_level_ascend;
        param.sort_by = "level";

        //更新并显示数据
        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });
        is_level_ascend = !is_level_ascend;
    };
    $scope.sort_by_star = function () {
        param.is_ascend = is_star_ascend;
        param.sort_by = "star";

        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });
        is_star_ascend = !is_star_ascend;
    };
    $scope.sort_by_grade_count = function () {
        param.is_ascend = is_grade_count_ascend;
        param.sort_by = "grade_count";

        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });
        is_grade_count_ascend = !is_grade_count_ascend;
    };
    $scope.sort_by_experience = function () {
        param.is_ascend = is_experience_ascend;
        param.sort_by = "experience";

        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });
        is_experience_ascend = !is_experience_ascend;
    };

    //设置当前选中页样式
    $scope.isActivePage = function (page) {
        return param.cur_page == page;
    };

    $scope.setAllUnselect = function () {
        var checks = document.getElementsByName("mycheckbox");
        var content = document.getElementById("select_all");
        content.innerHTML = "全选";
        for (var i = 0; i < checks.length; i++) {
            checks[i].checked = false;
        }
        isAllSelected = false;
    }

    //上一页
    $scope.previous = function () {
        if (param.cur_page - 1 >= 1) {
            $scope.selectPage(param.cur_page - 1);
            $scope.setAllUnselect();
        }
        else {
            alert("已到达第一页");
        }
    }

    //下一页
    $scope.next = function () {
        if (param.cur_page + 1 <= numOfPages) {
            $scope.selectPage(param.cur_page + 1);
            $scope.setAllUnselect();
        }
        else {
            alert("已到达最后一页");
        }
    };

    //页面跳转
    $scope.turn2SelPage = function (e) {
        var keyCode = window.event ? e.keyCode : e.which;
        if (keyCode == 13) {
            var page = $scope.input_page;
            if (1 <= page && page <= numOfPages) {
                $scope.selectPage(page);
            }
            else {
                alert("输入页面错误！");
            }
        }
    }
    //选择页面
    $scope.selectPage = function (page) {
        param.cur_page = page;
        //更新并显示数据
        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
            $scope.setAllUnselect();
        });
    }

    $scope.isFirstSelected = true;
    $scope.isSecondSelected = false;
    $scope.isThirdSelected = false;

    /*
     *选择每页显示的数据
     * */
    $scope.changePerPage = function (number) {
        param.per_page = number;
        param.cur_page = 1;

        //更新显示数据
        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.total_count / param.per_page);
            numOfPages = pageNum;
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });

        if (number == 20) {
            $scope.isFirstSelected = true;
            $scope.isSecondSelected = false;
            $scope.isThirdSelected = false;
        }
        else if (number == 50) {
            $scope.isFirstSelected = false;
            $scope.isSecondSelected = true;
            $scope.isThirdSelected = false;
        }
        else {
            $scope.isFirstSelected = false;
            $scope.isSecondSelected = false;
            $scope.isThirdSelected = true;
        }
    }

    /*
     * 控制删除的出现：选中复选框以及鼠标悬浮
     * */
    $scope.myClick = function (x) {
        if (!x.isSelected) {
            x.show = true;
            x.isSelected = true;
        }
        else {
            x.isSelected = false;
            x.show = false;
        }
    };

    $scope.myHover = function (x) {
        if (!x.isSelected) {
            x.show = true;
        }
    };
    $scope.myLeave = function (x) {
        if (!x.isSelected) {
            x.show = false;
        }
    };

    /*
     * 控制筛选栏的展开与收起
     * */
    $scope.control_filter = function () {
        if ($scope.show_filter) {
            $scope.show_filter = false;
            document.getElementById("filter_icon").style.color = "#aaaaaa";

            param.filter = null;
            {
                $scope.min_evaluation_number = null;
                $scope.max_evaluation_number = null;
                $scope.min_star = null;
                $scope.max_star = null;
                $scope.min_age = null;
                $scope.max_age = null;
                $scope.min_experience = null;
                $scope.max_experience = null;
                document.getElementById("level").innerHTML = "全部";
                $scope.province = null;
                $scope.city = null;
                $scope.useFilter = false;
            }

            loadDataService.loadData(param).then(function (result) {
                $scope.matrons = result.matrons;
                var pageNum = Math.ceil(result.records_count / param.per_page);
                var pageList = [];
                for (var i = 0; i < pageNum; i++) {
                    pageList.push(i + 1);
                }
                $scope.pages = pageList;
            });
        }
        else {
            $scope.show_filter = true;
            document.getElementById("filter_icon").style.color = "#5cb85c";
        }
    }

    /*
     * 筛选实现
     * */
    $scope.searchByFilter = function () {
        cur_page = 1;
        //获取uid以及access_token
        var access_token = $.cookie("access_token");
        var uid = sessionStorage.getItem("uid");

        if ($scope.useFilter) {
            var min_age = $scope.min_age;
            var max_age = $scope.max_age;
            if ((min_age == "") || (min_age == null)) {
                min_age = 1;
            }
            if ((max_age == "") || (max_age == null)) {
                max_age = 100;
            }
            var numRegExp = /\d+/;
            if (!numRegExp.test(min_age) || !numRegExp.test(max_age) || min_age < 0 || parseInt(min_age) > parseInt(max_age) || max_age > 100) {
                alert("请输入合理的年龄范围");
                return;
            }
            //工作经验改为范围筛选
            var min_experience = $scope.min_experience;
            var max_experience = $scope.max_experience;
            if ((min_experience == "") || (min_experience == null)) {
                min_experience = 0;
            }
            if ((max_experience == "") || (max_experience == null)) {
                max_experience = 100;
            }
            if (!numRegExp.test(min_experience) || !numRegExp.test(max_experience) || min_experience < 0 || parseInt(min_experience) > parseInt(max_experience) || max_experience > 100) {
                alert("请输入合理的工作经验范围");
                return;
            }

            var level = document.getElementById("level").innerHTML;
            var min_star = $scope.min_star;
            var max_star = $scope.max_star;
            if ((min_star == "") || (min_star == null)) {
                min_star = 1;
            }
            if ((max_star == "") || (max_star == null)) {
                max_star = 5;
            }
            if (!numRegExp.test(min_star) || !numRegExp.test(max_star) || min_star < 1 || parseInt(min_star) > parseInt(max_star) || max_star > 5) {
                alert("请输入合理的用户评分范围");
                return;
            }
            var min_evaluation_number = $scope.min_evaluation_number;
            var max_evaluation_number = $scope.max_evaluation_number;
            if ((min_evaluation_number == "") || (min_evaluation_number == null)) {
                min_evaluation_number = 0;
            }
            if ((max_evaluation_number == "") || (max_evaluation_number == null)) {
                max_evaluation_number = ~(1 << 31);
            }
            if (!numRegExp.test(min_evaluation_number) || !numRegExp.test(max_evaluation_number) || min_evaluation_number < 0 || parseInt(min_evaluation_number) > parseInt(max_evaluation_number)) {
                alert("请输入合理的评价数量范围");
                return;
            }
            param.filter = {};
            if ($scope.province == null) {
                param.filter.birth_place = "";
            } else if ($scope.city == null) {
                param.filter.birth_place = $scope.province.p
            } else {
                param.filter.birth_place = $scope.province.p + " " + $scope.city.n;
            }
            param.filter.age = {};
            param.filter.age.min = min_age;
            param.filter.age.max = max_age;
            param.filter.experience = {};
            param.filter.experience.min = min_experience;
            param.filter.experience.max = max_experience;
            if(level == "全部"){
                param.filter.level = 0;
            }
            else{
                param.filter.level = level;
            }
            param.filter.star = {};
            param.filter.star.min = min_star;
            param.filter.star.max = max_star;
            param.filter.evaluation_number = {};
            param.filter.evaluation_number.min = min_evaluation_number;
            param.filter.evaluation_number.max = max_evaluation_number;
        }

        //更新显示筛选的数据
        $scope.matrons = loadDataService.loadData(param).then(function (result) {
            $scope.matrons = result.matrons;
            var pageNum = Math.ceil(result.records_count / param.per_page);
            var pageList = [];
            for (var i = 0; i < pageNum; i++) {
                pageList.push(i + 1);
            }
            $scope.pages = pageList;
        });
    };
});

